package edu.pdx.LAMA.AndroidCourse.scheduler;

import java.util.ArrayList;
import java.util.Iterator;

import edu.pdx.LAMA.AndroidCourse.ModelLayer.EventDetails;
import edu.pdx.LAMA.AndroidCourse.ModelLayer.EventService;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;

public class EventPagerActivity extends FragmentActivity {
	
	private ViewPager viewPager;
	ArrayList<EventDetails> events;
	private String selectedDate;
	private Context context;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		viewPager = new ViewPager(this);
		viewPager.setId(R.id.viewPager);
		setContentView(viewPager);
		context = this;
		
		selectedDate = getIntent().getStringExtra(EventDetailsFragment.EXTRA_EVENT_DATE_SELECTED);
		
		EventService eventService = new EventService(this);
		//events = eventService.getDailyEvent();
		//events = (ArrayList<EventDetails>) eventService.getDatewiseEvents(selectedDate);
		events = (ArrayList<EventDetails>) eventService.getDailyEvents();
		ArrayList<EventDetails> temp = (ArrayList<EventDetails>) eventService.getDatewiseEvents(selectedDate);
		Iterator<EventDetails> it = temp.iterator();
		while(it.hasNext()){
			events.add(it.next());
		}
		
		FragmentManager fm = getSupportFragmentManager();
		viewPager.setAdapter(new FragmentStatePagerAdapter(fm) {
			
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return events.size();
			}
			
			@Override
			public Fragment getItem(int arg0) {
				// TODO Auto-generated method stub
				//EventDetails details = events.get(arg0);
				Log.d("abc", "inside the pager activity the index is "+arg0);
				
				return EventDetailsFragment.newInstance(arg0,selectedDate,context);
			}
		});
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				// TODO Auto-generated method stub
				EventDetails eDetails = events.get(arg0);
				if (eDetails.getTitle()!=null){
					setTitle(eDetails.getTitle());
				}
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		int eventIndex = (Integer) getIntent().getSerializableExtra(EventDetailsFragment.EXTRA_EVENT_SELECTED);
		for(int i=0;i<events.size();i++){
			if (i==eventIndex){
				viewPager.setCurrentItem(i);
				break;
			}
		}
	}
}
